package org.person.gift.rocketmq.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.person.gift.constants.OrderConstant;
import org.person.gift.domain.ShopCar;
import org.person.gift.dto.PlaceOrderDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 购物车服务,监听下订单事务消息,进行处理
 */
@Component
@RocketMQMessageListener(topic = OrderConstant.PLACE_ORDER_TX_TOPIC,
        consumerGroup = OrderConstant.PLACE_ORDER_TX_SHOP_CAR_CONSUMER_GROUP)
public class PlaceOrderClearShopCarMessageListener implements RocketMQListener<MessageExt> {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void onMessage(MessageExt message) {
        // 获取消息内容
        byte[] body = message.getBody();
        String string = new String(body);
        PlaceOrderDTO dto = JSONObject.parseObject(string, PlaceOrderDTO.class);

        Map<Long, Integer> skuInfos = dto.getSkuInfos();
        if(dto.getBuyNow() == 1){
            return;
        }
        // 如果是从购物车下单的话,删除该用户在购物车中已经下单的商品
        // 获取该用户在redis中的购物车数据
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps("shop_car_prefix_" + dto.getUserId());
        List<String> values = hashOps.values();
        if(values != null && values.size() > 0){
            // 获取当前已经被下单的商品的ID
            Set<Long> skuIds = skuInfos.keySet();
            // 循环被下单的商品
            for (Long skuId : skuIds) {
                // 从redis中获取该用户的购物车信息
                String shopCarStr = hashOps.get(skuId+"");
                if(StrUtil.isNotBlank(shopCarStr)){
                    ShopCar shopCar = JSONObject.parseObject(shopCarStr, ShopCar.class);
                    // 把删除状态设置为true
                    shopCar.setDelete(true);
                    // 再将删除的数据重新放入redis
                    hashOps.put(skuId+"",JSONObject.toJSONString(shopCar));
                }
            }
        }
    }
}